package com.jandan.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.jandan.logic.JWordzFacade;
import com.jandan.ui.client.util.ClientUtil;
import com.jandan.ui.model.CnAndSentence;
import com.jandan.ui.model.Word;

/**
 * 
 * 用于处理获取搜索单词ajax请求，返回json格式数据，请求路径在json-servlet.xml中配置，关于所使用的json处理包，参见相关文档
 * 这个类用于单词学习的客户端，可以先不用管
 * @author Gong Yong
 * @version 1.0
 *
 */
public class SearchWordController implements Controller {
	private JWordzFacade jwordz;

	public void setJwordz(JWordzFacade jwordz) {
		this.jwordz = jwordz;
	}

	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		String word = request.getParameter("word");
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
//		String wordLibID = request.getParameter("wordLibID");
		
		int s = start == null ? 0 : Integer.parseInt(start);
		int l = limit == null ? 10 : Integer.parseInt(limit);
		
		String q = request.getParameter("q");
		if(q != null){
			word = q;
		}
		
		int count = jwordz.getSearchedWordCount(word,ClientUtil.STANDARD_WORDLIB_ID);
		List<Word> wordList = jwordz.getSearchedWordList(word,s,l,ClientUtil.STANDARD_WORDLIB_ID);
		
		Map model = new HashMap();
		model.put("totalCount", count);

		Iterator<Word> it = wordList.iterator();
		
		ArrayList list = new ArrayList();
		Word w = null;
		Map map = null;
		StringBuffer wordCn = null;
		CnAndSentence cs = null;
		while(it.hasNext()){
			w = it.next();
			if(w != null){
				map = new HashMap();
				map.put("wordID", w.getWordID());
				map.put("wordEn", w.getWordEn());
				map.put("phonetics", w.getPhonetics());
				
				wordCn = new StringBuffer();
				List<CnAndSentence> csList = w.getCnAndSentenceList();
				for(int i = 0,n = csList.size();i < n;i++){
					cs = csList.get(i);
					if(cs != null){
						if(i == 0){
							wordCn.append(cs.getCn());
						}
						else {
							wordCn.append(";");
							wordCn.append(cs.getCn());
						}
					}
				}			
				map.put("wordCn",wordCn);
				list.add(map);
			}
		}
		
		model.put("words", list);

		return new ModelAndView("jsonView",model);
	}
}
